﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
using DevExpress.Web.ASPxUploadControl;
using ITViet.Web.App_Code;
using ITViet.Domains;

namespace ITViet.Web.Controls
{
  public partial class ImageUpload : AdminBaseControl
  {
    #region Variables and properties
    public string UploadCompleteFunction = string.Empty;
    public string UploadSessionName = string.Empty;
    public string UploadFolder = FolderDirector.TempFolder;
    public string NoticeMessage = string.Empty;

    public string ImagePath
    {
      get
      {
        return hfImagePath.Value;
      }
      set
      {
        hfImagePath.Value = value;
      }
    }
    #endregion

    #region Methods
    private string SavePostedFile(UploadedFile uploadedFile)
    {
      string ret = "";
      if (uploadedFile.IsValid)
      {
        try
        {
          string tempFileName = (Page as AdminBasePage).CurrentUser.Username + "_" + Utils.GetDateTimeNumber(DateTime.Now) + ".jpg";
          string fileName = MapPath(FolderDirector.TempFolder) + tempFileName;
          if (Session[UploadSessionName] != null)
          {
            File.Delete(Session[UploadSessionName].ToString());
          }
          uploadedFile.SaveAs(fileName);
          Session[UploadSessionName] = fileName;
          ret = tempFileName + "|" + uploadedFile.FileName;
        }
        catch (Exception ex)
        {
          WriteLog("ImageUpload.ascx.cs::Save Posted File", ex);
          ret = "ERROR|" + Resources.Messages.ERR0004;
        }
      }
      return ret;
    }

    public void HideUpload()
    {
      uploader.Visible = false;
      lblNotice.Visible = false;
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      hfImagePath.Value = ImagePath;
      if (string.IsNullOrEmpty(ImagePath))
        imagePreview.ImageUrl = FolderDirector.PreviewImage;
      else
        imagePreview.ImageUrl = "../" + ImagePath;
    }

    protected void uploader_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
    {
      string result = SavePostedFile(e.UploadedFile);
      if (result.IndexOf("ERROR") >= 0)
      {
        e.IsValid = false;
        e.ErrorText = string.Empty;
      }
      e.CallbackData = result;
    }
    #endregion
  }
}